#include <xp/net/tcp.h>
#include <xp/net/inet.h>
#include <xp/bas/stdio.h>
#include <xp/bas/stdlib.h>
#include <xp/bas/mstring.h>
#include <xp/bas/string.h>
#include <xp/bas/endian.h>

int xp_main (int argc, xp_char_t* argv[])
{
	xp_tcp_t tcp;

	xp_byte_t* ip;
	xp_size_t iplen;

	xp_uint16_t port;
	int mode;

	if (argc != 3) {
		xp_printf (XP_TEXT("usage: %s port mode\n"), argv[0]);
		xp_printf (XP_TEXT(" where mode := 4 | 6\n"));
		return -1;
	}

	port = xp_atoi(argv[1]);
	mode = xp_atoi(argv[2]);

	if (mode != 4 && mode != 6) {
		xp_printf (XP_TEXT("error: mode should be either 4 or 6\n"));
		return -1;
	}

	xp_printf (XP_TEXT("port: %d mode: %d\n"), (int)port, mode);

	xp_sckstartup ();

	if (xp_tcp_open(&tcp, XP_TCP_TEXT) == XP_NULL) {
		xp_printf (XP_TEXT("cannot open tcp\n"));
		return -1;
	}

	xp_tcp_settmout (&tcp, XP_TCP_RECV, 5000);

	if (mode == 4) {
		ip = xp_inet4_loopback;
		iplen = xp_sizeof(xp_inet4_loopback);
	}
	else {
		ip = xp_inet6_loopback;
		iplen = xp_sizeof(xp_inet6_loopback);
	}

	if (xp_tcp_conn(&tcp, xp_hton16(port), ip, iplen, 0) == -1) {
		xp_printf (XP_TEXT("cannot connect\n"));
		xp_tcp_close (&tcp);
		return -1;
	}

	{
		xp_char_t buf[1000];
		xp_ssize_t n;

		xp_strxcpy (buf, xp_countof(buf), XP_TEXT("nice\n"));
		n = xp_tcp_send (&tcp, buf, xp_strlen(buf));
		if (n == -1) {
			xp_printf (XP_TEXT("cannot send data\n"));
			xp_tcp_close (&tcp);
			return -1;
		}

		n = xp_tcp_recv (&tcp, buf, xp_countof(buf));
		if (n == -1) {
			xp_printf (XP_TEXT("cannot receive data\n"));
			xp_tcp_close (&tcp);
			return -1;
		}
		buf[n] = '\0';

		xp_printf (XP_TEXT("%s\n"), buf);
	}

	xp_tcp_close (&tcp);
	return 0;
}

